package com.splant.android.smart.UILevel.Community;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.hiflying.smartlink.OnSmartLinkListener;
import com.hiflying.smartlink.SmartLinkedModule;
import com.hiflying.smartlink.v3.SnifferSmartLinker;
import com.splant.android.R;
import com.splant.android.smart.SystemDefinedLevel.GenericControls.Dialog.LoadingDialog;

public class Garden_WifiConnect_Activity extends Activity implements OnSmartLinkListener, View.OnClickListener {

    private EditText edt_ssid;
    private EditText edt_psw;
    private Button btn_enter;
    private boolean mIsConncting = false;
    protected SnifferSmartLinker mSnifferSmartLinker;
    protected Handler mViewHandler = new Handler();
    private TextView tv_deviceMac;
    private Button btn_goBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.garden_wificonnect_activity);

        btn_goBack = (Button) findViewById(R.id.btn_goBack);
        edt_ssid = (EditText) findViewById(R.id.edt_ssid);
        edt_psw = (EditText) findViewById(R.id.edt_psw);
        btn_enter = (Button) findViewById(R.id.btn_enter);

        tv_deviceMac = (TextView) findViewById(R.id.tv_deviceMac);

        btn_goBack.setOnClickListener(this);
        btn_enter.setOnClickListener(this);

        edt_ssid.setText(getSSid());

        loadingDialog = LoadingDialog.createDialog(this);

        mSnifferSmartLinker = SnifferSmartLinker.getInstence();

        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

        registerReceiver(mWifiChangedReceiver, intentFilter);
    }
    @Override
    public void onLinked(final SmartLinkedModule smartLinkedModule) {

        mViewHandler.post(new Runnable() {
            @Override
            public void run() {

                String macAddr = smartLinkedModule.getMac();
                if (macAddr.equals("") == false) {
                    String mac = "";
                    char[] macChars = macAddr.toCharArray();
                    for (int i = 0; i < macChars.length; i++) {
                        if (i > 0 && i % 2 == 0)
                            mac += ":";
                        mac += macChars[i];
                    }
                    tv_deviceMac.setText("模块MAC：" + mac);
                }
            }
        });

    }

    @Override
    public void onCompleted() {
        mViewHandler.post(new Runnable() {
            @Override
            public void run() {

                Toast.makeText(Garden_WifiConnect_Activity.this, "配对成功！", Toast.LENGTH_SHORT).show();
                loadingDialog.dismiss();
                mIsConncting = false;
            }
        });
    }

    @Override
    public void onTimeOut() {
        mViewHandler.post(new Runnable() {
            @Override
            public void run() {

                Toast.makeText(Garden_WifiConnect_Activity.this, "配对超时！", Toast.LENGTH_SHORT).show();

                loadingDialog.dismiss();
                mIsConncting = false;

            }
        });
    }

    private LoadingDialog loadingDialog;

    private void connectWifi() {
        if (mIsConncting == false) {
            //设置要配置的ssid 和pswd
            try {
                mSnifferSmartLinker.setOnSmartLinkListener(Garden_WifiConnect_Activity.this);
                //开始 smartLink
                mSnifferSmartLinker.start(this, edt_psw.getText().toString().trim(), edt_ssid.getText().toString().trim());
                mIsConncting = true;

                if (loadingDialog.isShowing() == false)
                    loadingDialog.show();

            } catch (Exception e) {

                e.printStackTrace();
            }
        }
    }

    private String getSSid() {

        WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        if (wm != null) {
            WifiInfo wi = wm.getConnectionInfo();
            if (wi != null) {
                String ssid = wi.getSSID();
                if (ssid.length() > 2 && ssid.startsWith("\"") && ssid.endsWith("\"")) {
                    return ssid.substring(1, ssid.length() - 1);
                } else {
                    return ssid;
                }
            }
        }
        return "";
    }

    private BroadcastReceiver mWifiChangedReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //获取manager
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            //获取wifi状态
            NetworkInfo.State state = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
            if (state != NetworkInfo.State.CONNECTED) {

                edt_psw.requestFocus();
                btn_enter.setEnabled(false);

                if (loadingDialog.isShowing())
                    loadingDialog.dismiss();

                Toast.makeText(context, "WIFI已断开连接", Toast.LENGTH_SHORT).show();

            } else if (state == NetworkInfo.State.CONNECTED) {

                edt_ssid.setText(getSSid());
                edt_psw.requestFocus();
                btn_enter.setEnabled(true);

                Toast.makeText(context, "WIFI已连接", Toast.LENGTH_SHORT).show();
            }
        }
    };


    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btn_goBack:
                finish();
                break;
            case R.id.btn_enter:
                connectWifi();
                break;
        }
    }

}
